#include <iostream>
#include "stlfutils.h"
#include "cbbuildmgr.h"
#include "tinyxml.h"

CCodeBlocksBuildManager::CCodeBlocksBuildManager( void ) {
  Clear();
}

CCodeBlocksBuildManager::~CCodeBlocksBuildManager( void ) {
  Clear();
}

void CCodeBlocksBuildManager::Clear( void ) {
  m_ProjectLoaded = false;
  m_WorkspaceLoaded = false;
  M_Code_Project.Clear();
  M_Code_Workspace.Clear();
}

bool CCodeBlocksBuildManager::LoadProjectOrWorkspace( const CString& FileName ) {
  bool result = false;
  TiXmlDocument cbpw;
  result = cbpw.LoadFile( FileName.GetCString() );
  if( !result ) {
    return false;
  }
  Clear();
  const TiXmlElement *root = cbpw.RootElement();
  if( 0 == strcmp( root->Value(), "CodeBlocks_project_file" ) ) {
    M_Code_Project.Read( root );
    m_ProjectLoaded = true;
    result = true;
  } else if( 0 == strcmp( root->Value(), "CodeBlocks_workspace_file" ) ) {
    M_Code_Workspace.Read( root );
    M_Code_Workspace.LoadWorkspaceProjects( ExtractFilePath( FileName ) );
    m_WorkspaceLoaded = true;
    result = true;
  }
  return result;
}

void CCodeBlocksBuildManager::Show( void ) {
  if( m_ProjectLoaded ) {
    std::cout << "Loaded file is Code::Blocks project." << std::endl;
    M_Code_Project.Show();
  } else if( m_WorkspaceLoaded ) {
    std::cout << "Loaded file is Code::Blocks workspace." << std::endl;
    M_Code_Workspace.Show();
  } else {
    std::cout << "No project or workspace loaded." << std::endl;
  }
}

void CCodeBlocksBuildManager::GenerateMakefile( const CString& FileName ) {
  if( m_ProjectLoaded ) {
    M_Code_Project.GenerateMakefile( FileName, m_Config );
  }
  if( m_WorkspaceLoaded ) {
    M_Code_Workspace.GenerateMakefile( FileName, m_Config );
  }
}

//------------------------------------------------------------------------------
